package common
import (
	"time"
	"os"
	"log"
	"runtime"
	"strconv"
)

type log4go struct {
	logFile *os.File
	logger  *log.Logger
}

const (
	LOG_DEBUG = iota
	LOG_WARNING
	LOG_FATAL
	LOG_INFO
)

const (
	LOG_DIR_PATH = "./log"
)

func Logger(logType int, msg string) {
	instance := newLog4go()

	switch logType{
	case LOG_DEBUG:
		instance.println("[debug] "+msg)
	case LOG_WARNING:
		instance.println("[warning] "+msg)
	case LOG_FATAL:
		instance.fatal("[fatal] "+msg)
	case LOG_INFO:
		instance.println("[info] "+msg)
	}
}

func newLog4go() *log4go {
	myTime := NewMyTime(time.Now())
	os.Mkdir(LOG_DIR_PATH, 0777)

	fileName := "/log_" + myTime.Year + myTime.Month + myTime.Day+".log"
	realPath := LOG_DIR_PATH + fileName

	logFile, err := os.OpenFile(realPath, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0777)

	if err != nil {
		panic(err.Error())
	}

	logger := log.New(logFile, "", log.Ldate|log.Ltime)

	return &log4go{
		logFile: logFile,
		logger: logger,
	}
}

func (self *log4go)convMsg(logStr string) string {
	_, file, line, _ := runtime.Caller(3)
	return file + ":" + strconv.Itoa(line) + " " + logStr
}

func (self *log4go)println(logStr string) {
	defer self.logFile.Close()
	msg := self.convMsg(logStr)
	self.logger.Println(msg);
}

func (self *log4go)fatal(logStr string) {
	defer self.logFile.Close()
	msg := self.convMsg(logStr)
	self.logger.Fatal(msg);
}
